package com.jf.service.impl;

import com.jf.bean.Token;
import com.jf.bean.Userinfo;
import com.jf.dao.TokenDao;
import com.jf.dao.impl.TokenDaoImpl;
import com.jf.service.TokenService;
import com.jf.util.MyUtils;

import java.util.Date;

public class TokenServiceImpl implements TokenService {
    private TokenDao tokenDao = new TokenDaoImpl();
    @Override
    public String getToken(int userinfoId) {
        /*封装token*/
        Token token = tokenDao.getByUserId(userinfoId);
        Date date = new Date();
        date.setDate(date.getDate() + 7);
        if (token == null) {
            token = new Token();
            token.setLoginId(userinfoId);
            token.setToken(MyUtils.getUUID());
            token.setExpires(date);
            /*存储token*/
            tokenDao.add(token);
        } else {
            token.setToken(MyUtils.getUUID());
            token.setExpires(date);
            tokenDao.update(token);
        }
        return token.getToken();
    }

    @Override
    public boolean isLogin(String token) {
        Token tokenBean = tokenDao.getByToken(token);
        if(tokenBean != null){
//            Date d = new Date();
//            System.out.println(d.getTime());
            /*获取当前系统的时间戳*/
//            System.out.println(System.currentTimeMillis());
            return tokenBean.getExpires().getTime() > System.currentTimeMillis();
        }
        return false;
    }

    @Override
    public void logout(String token) {
        tokenDao.delete(token);
    }

    @Override
    public Userinfo getUserByToken(String token) {
        return tokenDao.getUserByToken(token);
    }
}
